﻿Imports Microsoft.Practices.EnterpriseLibrary.Logging

Partial Class _Translate
    Inherits System.Web.UI.Page
    Const Category As String = "Translate.aspx"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then


            Const LogTitle As String = "Page_Load"
            Dim LogProperties As Dictionary(Of String, Object)
            Logger.Write(LogTitle & " -> Start.", Category, 10, 0, Diagnostics.TraceEventType.Start, LogTitle)

            If Session("User") Is Nothing Then
                Logger.Write("Session expited.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle)
                Session("ErrorMessage") = "Session expired. Please login!"
                Response.Redirect("Error.aspx")
            Else
                UserAccount.Text = Session("User").ToString
                LogProperties = General.CreateLogProperties(UserAccount.Text)
                Dim AllProjects As System.Xml.XmlNodeList
                AllProjects = XMLFile.GetUserFile.SelectNodes("/users/user[@email=""" & UserAccount.Text.ToLower & """]/project")
                If AllProjects.Count = 0 Then
                    Logger.Write("No project returned for user '" & UserAccount.Text & "'.", Category, 100, 0, Diagnostics.TraceEventType.Information, LogTitle, LogProperties)
                    Session("ErrorMessage") = "You are not registered for any project."
                    Response.Redirect("Error.aspx")
                Else
                    Logger.Write("Found " & AllProjects.Count & " projects for user '" & UserAccount.Text & "'.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                    Dim Project As String = CStr(Session("Project"))
                    Dim Languages As String = CStr(Session("Languages"))
                    If Project Is Nothing Then
                        Logger.Write("No project selected so far.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                        Project = AllProjects(0).InnerText
                        Session("Project") = Project
                        Languages = AllProjects(0).Attributes("lang").InnerText
                        Session("Languages") = Languages
                        Logger.Write("Set first project '" & Project & "' as current project.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                    End If
                    SelectedProject.Text = Project
                    With MyProjects
                        .DataSource = AllProjects
                        .DataBind()
                    End With

                    Dim Directory As String = ConfigurationManager.AppSettings("ProjectDirectory").ToString & Project & "\"
                    If Languages.Contains(",") Then
                        Languages = Left(Languages, InStr(Languages, ",") - 1)
                    End If
                    Logger.Write("Getting '" & Directory & Languages & ".xml'.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                    Dim LanguageXML As System.Xml.XmlDocument
                    If Not IO.File.Exists(Directory & Languages & ".xml") Then
                        Logger.Write("Language file '" & Directory & Languages & ".xml' does not exist.", Category, 100, 0, Diagnostics.TraceEventType.Information, LogTitle, LogProperties)
                        XMLFile.ComputePercentage(Project, Languages, Nothing, LogProperties)
                    End If
                    If Not IO.File.Exists(Directory & Languages & ".xml") Then
                        Logger.Write("Language file '" & Directory & Languages & ".xml' does not exist.", Category, 200, 0, Diagnostics.TraceEventType.Error, LogTitle, LogProperties)
                        Session("ErrorMessage") = "Language file for '" & Languages & "' does not exist!"
                        Response.Redirect("Error.aspx")
                    Else
                        LanguageXML = XMLFile.GetXMLDocument(Directory & Languages & ".xml")
                        Dim AllFiles As System.Xml.XmlNodeList
                        AllFiles = LanguageXML.SelectNodes("/files[@language=""" & Languages & """]/file")
                        Dim oDs As New Data.DataSet
                        oDs.ReadXml(Directory & Languages & ".xml")
                        With FileList
                            .DataSource = oDs.Tables(1)
                            .DataBind()
                        End With

                        'Logger.Write(AllFiles.Count & " files defined for '" & Languages & "' in Project '" & Project & "'.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                        'If AllFiles.Count = 0 Then
                        '    Session("ErrorMessage") = "No files defined for '" & Languages & "' in Project '" & Project & "'."
                        '    Response.Redirect("Error.aspx")
                        'Else
                        '    With FileList
                        '        .DataSource = AllFiles
                        '        .DataBind()
                        '    End With
                        '    Dim SingleFile As System.Xml.XmlNode
                        '    For Each SingleFile In AllFiles

                        '    Next
                        'End If
                    End If


                    'Check whether a file is selected
                    If Session("SelectedFilename") Is Nothing Then
                        Logger.Write("No file selected currently.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                        'Show summary
                        'CurrentFile.Text = String.Empty
                        Save.Visible = False
                        CurrentFile.Text = "Summary"
                        Dim Summary As New Data.DataTable
                        Summary = XMLFile.ComputeSummary(CStr(Session("Project")))
                        Logger.Write("Summary for project '" & CStr(Session("Project")) & " contains " & Summary.Rows.Count.ToString & " rows.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                        With SummaryRepeater
                            .DataSource = Summary
                            .DataBind()
                            .Visible = True
                        End With
                    Else
                        SummaryRepeater.Visible = False
                        CurrentFile.Text = CStr(Session("SelectedFilename"))
                        Logger.Write("Selected filename: '" & CurrentFile.Text & "'.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                        Dim EnglishFile, TranslatedFile As System.Xml.XmlDocument
                        EnglishFile = XMLFile.GetXMLDocument(Directory & CurrentFile.Text & ".resx")
                        TranslatedFile = XMLFile.GetXMLDocument(Directory & Languages & "\" & CurrentFile.Text & "." & Languages & ".resx")
                         Dim Table As New Data.DataTable
                        Table.Columns.Add("TextName")
                        Table.Columns.Add("English")
                        Table.Columns.Add("Translation")
                        Dim Row As Data.DataRow
                        Dim Text, Translated As System.Xml.XmlNode
                        For Each Text In EnglishFile.SelectNodes("/root/data")
                            Row = Table.NewRow
                            Row.Item("TextName") = HttpUtility.HtmlEncode(Text.Attributes("name").InnerText)
                            Row.Item("English") = HttpUtility.HtmlEncode(Text.SelectSingleNode("value").InnerText)
                            Translated = TranslatedFile.SelectSingleNode("/root/data[@name=""" & _
                                Row.Item("Textname").ToString & """]/value")
                            If Translated Is Nothing Then
                                Row.Item("Translation") = String.Empty
                            Else
                                Row.Item("Translation") = Translated.InnerText 'HttpUtility.HtmlEncode(Translated.InnerText)
                            End If
                            Table.Rows.Add(Row)
                        Next
                        TextElements.DataSource = Table
                        TextElements.DataBind()
                        Save.Visible = True
                    End If




                    'For Each SingleProject In AllProjects
                    '    FileList.DataSource = AllProjects

                    '    AddProject = New ListItem(SingleProject.InnerText)
                    '    If Project = SingleProject.InnerText Then
                    '        AddProject.Selected = True
                    '    End If
                    '    UserProjects.Items.Add(AddProject)
                    'Next
                    End If



            End If
        End If
    End Sub

    Protected Sub FileList_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles FileList.RowCommand
        If e.CommandName.CompareTo("EditFile") = 0 Then
            Const LogTitle As String = "EditFile"

            Dim LogProperties As Dictionary(Of String, Object)
            Logger.Write(LogTitle & " -> Start.", Category, 10, 0, Diagnostics.TraceEventType.Start, LogTitle)

            If CStr(Session("User")).Length = 0 Then
                Logger.Write("Session expired.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle)
                Session("ErrorMessage") = "Session expired. Please login!"
                Response.Redirect("Error.aspx")
            Else
                LogProperties = General.CreateLogProperties(CStr(Session("User")))
                Dim Filename As String = Nothing
                Try
                    Filename = FileList.DataKeys(Convert.ToInt32(e.CommandArgument)).Value.ToString
                    If Filename.Length = 0 Then
                        Logger.Write("No file selected.", Category, 200, 0, Diagnostics.TraceEventType.Error, LogTitle, LogProperties)
                        Session("ErrorMessage") = "No file selected"
                    End If
                Catch ex As Exception
                    Logger.Write("Error computing selected filename: " & ex.Message, Category, 200, 0, Diagnostics.TraceEventType.Error, LogTitle, LogProperties)
                    Session("ErrorMessage") = ex.Message
                End Try
                If Filename.Length = 0 Then
                    Response.Redirect("Error.aspx")
                Else
                    Logger.Write("Selected filename: '" & Filename & "'.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                    Session("SelectedFilename") = Filename
                    Response.Redirect("Translate.aspx")
                End If

            End If
        End If
    End Sub

    Protected Sub MyProjects_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles MyProjects.RowCommand
        If e.CommandName.CompareTo("SwitchProject") = 0 Then
            Const LogTitle As String = "SwitchProject"

            Dim LogProperties As Dictionary(Of String, Object)
            Logger.Write(LogTitle & " -> Start.", Category, 10, 0, Diagnostics.TraceEventType.Start, LogTitle)

            If CStr(Session("User")).Length = 0 Then
                Logger.Write("Session expired.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle)
                Session("ErrorMessage") = "Session expired. Please login!"
                Response.Redirect("Error.aspx")
            Else
                LogProperties = General.CreateLogProperties(CStr(Session("User")))
                Dim ProjectName As String = Nothing
                Try
                    ProjectName = MyProjects.DataKeys(Convert.ToInt32(e.CommandArgument)).Value.ToString
                    If ProjectName.Length = 0 Then
                        Logger.Write("No project selected.", Category, 200, 0, Diagnostics.TraceEventType.Error, LogTitle, LogProperties)
                        Session("ErrorMessage") = "No project selected"
                    End If
                Catch ex As Exception
                    Logger.Write("Error computing selected projectname: " & ex.Message, Category, 200, 0, Diagnostics.TraceEventType.Error, LogTitle, LogProperties)
                    Session("ErrorMessage") = ex.Message
                End Try
                If ProjectName.Length = 0 Then
                    Response.Redirect("Error.aspx")
                Else
                    Logger.Write("Selected projectname: '" & ProjectName & "'.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                    Session("Project") = ProjectName
                    Session.Remove("SelectedFilename")
                    Response.Redirect("Translate.aspx")
                End If

            End If
        End If
    End Sub

    Protected Sub Save_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Save.Click
        Const LogTitle As String = "Save"

        Dim LogProperties As Dictionary(Of String, Object)
        Logger.Write(LogTitle & " -> Start.", Category, 10, 0, Diagnostics.TraceEventType.Start, LogTitle)

        If CStr(Session("User")).Length = 0 Then
            Logger.Write("Session expired.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle)
            Session("ErrorMessage") = "Session expired. Please login!"
            Response.Redirect("Error.aspx")
        Else
            LogProperties = General.CreateLogProperties(CStr(Session("User")))


            Dim Item As RepeaterItem
            Dim TB As TextBox
            Dim LB As Label
            Dim TranslatedFile As System.Xml.XmlDocument
            Dim EnglishFile As System.Xml.XmlDocument
            Dim Project As String = CStr(Session("Project"))
            If Project Is Nothing Then
                Logger.Write("Could not find Sessionvalue for selected Project!", Category, 200, 0, Diagnostics.TraceEventType.Error, LogTitle, LogProperties)
                Session("ErrorMessage") = "Session expired. Could not read Project. Please login!"
                Response.Redirect("Error.aspx")
            End If
            Dim Languages As String = CStr(Session("Languages"))
            If Languages Is Nothing Then
                Logger.Write("Could not find Sessionvalue for selected Language!", Category, 200, 0, Diagnostics.TraceEventType.Error, LogTitle, LogProperties)
                Session("ErrorMessage") = "Session expired. Could not read Language. Please login!"
                Response.Redirect("Error.aspx")
            End If
            Dim ElementName As String
            Dim NewValue, CurrentValue As String
            Dim Node As System.Xml.XmlNode
            Dim Updates As Integer = 0
            Dim Directory As String = ConfigurationManager.AppSettings("ProjectDirectory").ToString & Project & "\"

            EnglishFile = XMLFile.GetXMLDocument(Directory & CurrentFile.Text & ".resx")
            Dim TargetFilename As String = Directory & Languages & "\" & CurrentFile.Text & "." & Languages & ".resx"


            TranslatedFile = XMLFile.GetXMLDocument(targetFilename)
            Dim Filename As String = CurrentFile.Text
            Logger.Write("Checking for changes in '" & Filename & "'...", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
            For Each Item In TextElements.Items
                LB = Item.FindControl("Element")
                TB = Item.FindControl("TranslatedText")
                ElementName = LB.Text
                Node = TranslatedFile.SelectSingleNode("/root/data[@name=""" & _
                                                ElementName & """]/value")
                If Node Is Nothing Then
                    Logger.Write("Node '" & ElementName & "' does not exist in translation file yet. Adding...", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                    Node = EnglishFile.SelectSingleNode("/root/data[@name=""" & ElementName & """]")
                    Dim rootnode As System.Xml.XmlNode = TranslatedFile.SelectSingleNode("/root")
                    Dim CopiedNode As System.Xml.XmlNode = TranslatedFile.ImportNode(Node, True)
                    CopiedNode.SelectSingleNode("value").InnerText = TB.Text

                    rootnode.AppendChild(CopiedNode)
                    Updates += 1

                    Logger.Write("Added value to empty node '" & ElementName & "'.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                Else
                    CurrentValue = Node.InnerText
                    NewValue = TB.Text
                    If CurrentValue = NewValue Then
                        Logger.Write("Value of '" & ElementName & "' did not change.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                    Else
                        Logger.Write("Updated value of '" & ElementName & "'.", Category, 100, 0, Diagnostics.TraceEventType.Information, LogTitle, LogProperties)
                        Node.InnerText = NewValue
                        Updates += 1
                    End If
                End If
            Next
            If Updates = 0 Then
                Logger.Write("No updates made. No need to save '" & TargetFilename & "'.", Category, 100, 0, Diagnostics.TraceEventType.Information, LogTitle, LogProperties)
                Session("GlobalMessage") = "No updates made. No need to save file."
            Else
                Logger.Write(Updates.ToString & " updates made. Saving file '" & TargetFilename & "'.", Category, 100, 0, Diagnostics.TraceEventType.Information, LogTitle, LogProperties)
                TranslatedFile.Save(TargetFilename)
                Logger.Write("File saved successfully.", Category, 100, 0, Diagnostics.TraceEventType.Information, LogTitle, LogProperties)
                If General.CreateBackup(TranslatedFile, TargetFilename, LogProperties) Then
                    Logger.Write("Created backup file successfully.", Category, 100, 0, Diagnostics.TraceEventType.Information, LogTitle, LogProperties)
                Else
                    Logger.Write("Backup file was not created! Please check.", Category, 200, 0, Diagnostics.TraceEventType.Warning, LogTitle, LogProperties)
                End If
                XMLFile.ComputePercentage(Project, Languages, CurrentFile.Text, LogProperties)
                Logger.Write("Updated Percentages of '" & CurrentFile.Text & "'. ", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                Session("GlobalMessage") = "File '" & TargetFilename.Split("\".ToCharArray)(TargetFilename.Split("\".ToCharArray).GetUpperBound(0)) & "' saved sucessfully!"
                If General.FTPUploadEnabled(Project, LogProperties) Then
                    Try
                        General.FTPUpload(Project, TargetFilename, LogProperties)
                        Logger.Write("FTP Uploade successfull.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
                    Catch ex As Exception
                        Logger.Write("Error while FTP Upload: " & ex.Message, Category, 300, 0, Diagnostics.TraceEventType.Error, LogTitle, LogProperties)
                        Session("GlobalMessage") &= "Error while uploading file via FTP!"
                    End Try
                End If
            End If
            Session.Remove("SelectedFilename")
            Logger.Write("Removed Session 'SelectedFilename'.", Category, 10, 0, Diagnostics.TraceEventType.Verbose, LogTitle, LogProperties)
            Response.Redirect("Translate.aspx")
        End If

    End Sub

    ''' <summary>
    ''' Colorize Background to differ between translated and not-translated text easily
    ''' </summary>
    ''' <param name="translationText"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function IsTranslatedCSS(translationText As Object) As String
        If CStr(translationText) = String.Empty Then
            Return "nottranslated"
        Else
            Return "translated"
        End If
    End Function


End Class
